package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.entity.AttendanceRulesVO;
import com.wtwd.campus.service.AttendanceRulesService;
import com.wtwd.campus.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.ArrayList;
import java.util.Map;

/**
 * @Author px
 * @Date 2021年12月9日 14:47:11
 * @Description 考勤规则设置
 */
@RestController
@RequestMapping("/attendanceRules")
public class AttendanceRuleController {

    private static final Logger logger = LoggerFactory.getLogger(AttendanceDeviceController.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private AttendanceRulesService attendanceRulesService;

    /**
     * 新增考勤规则
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/addAttendanceRules")
    @Transactional
    public RespEntity addAttendanceRules(@RequestBody AttendanceRulesVO data, HttpServletRequest request) {
        Integer userId = getUserId(request);
        if (userId == null) {
            return new RespEntity(RespCode.USER_NOT_FOUNT);
        }
        ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) JSON.parseObject(data.getData(), ArrayList.class);
        data.setDataList(list);
        logger.info("/addAttendanceRules,data={}", data.toString());
        data.setCreateUser(userId);
        data.setCreateTime(System.currentTimeMillis());
        //校验名称，同一学校不可重复
        boolean b = attendanceRulesService.judgeAttendanceRuleName(data.getName(), data.getSchoolId());
        if (b) {
            int i = attendanceRulesService.addAttendanceRule(data);
            return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
        } else {
            return new RespEntity(RespCode.ATTENDANCE_RULE_NAME_EXISTS);
        }
    }

   /* public static void main(String[] args) {
        String a="[{'a':10,'b':20},{'a':10,'b':20}]";
        ArrayList<Map<String,Object>> list = (ArrayList<Map<String,Object>>) JSON.parseObject(a, ArrayList.class);
        System.out.println(list.get(0).get("a"));
    }*/

    /**
     * 查询某个学校的考勤规则
     *
     * @param schoolId
     * @param request
     * @return
     */
    @GetMapping("/getSchoolAttendanceRules/{schoolId}/{currPage}/{pageSize}")
    @Transactional
    public RespEntity getSchoolAttendanceRules(@PathVariable("schoolId") Integer schoolId, @PathVariable("currPage") Integer currPage,
                                               @PathVariable("pageSize") Integer pageSize, HttpServletRequest request) {
        Integer userId = getUserId(request);
        if (userId == null) {
            return new RespEntity(RespCode.USER_NOT_FOUNT);
        }
        logger.info("/getSchoolAttendanceRules,schoolId={},curPage={},pageSize={}", schoolId.toString(), currPage.toString(), pageSize.toString());
        Map<String, Object> result = attendanceRulesService.getAttendanceRulesList(schoolId, currPage, pageSize);
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * 根据id查询一个年级的考勤信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/getAttendanceRulesById/{id}")
    @Transactional
    public RespEntity getAttendanceRulesById(@PathVariable("id") Integer id, HttpServletRequest request) {
        Integer userId = getUserId(request);
        if (userId == null) {
            return new RespEntity(RespCode.USER_NOT_FOUNT);
        }
        logger.info("/getAttendanceRulesById,schoolId={}", id.toString());
        AttendanceRulesVO result = attendanceRulesService.getAttendanceRulesById(id);
        return new RespEntity(RespCode.SUCCESS, result);
    }


    /**
     * 修改考勤信息
     *
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/modifyAttendanceRules")
    @Transactional
    public RespEntity modifyAttendanceRules(@RequestBody AttendanceRulesVO data, HttpServletRequest request) {
        Integer userId = getUserId(request);
        if (userId == null) {
            return new RespEntity(RespCode.USER_NOT_FOUNT);
        }
        ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) JSON.parseObject(data.getData(), ArrayList.class);
        data.setDataList(list);
        logger.info("/modifyAttendanceRules,data={}", data.toString());
        //根据id查询一笔考勤信息
        AttendanceRulesVO attendanceRulesById = attendanceRulesService.getAttendanceRulesById(data.getId());
        if (attendanceRulesById == null) {
            return new RespEntity(RespCode.ATTENDANCE_NOT_EXISTS);
        }
        boolean flag = attendanceRulesById.getName().equals(data.getName()) ? true : false;
        boolean ifDo = true;
        if (!flag) {
            //校验名称，同一学校不可重复
            boolean b = attendanceRulesService.judgeAttendanceRuleName(data.getName(), data.getSchoolId());
            ifDo = b ? true : false;
        }
        if (ifDo) {
            int i = attendanceRulesService.modifyAttendanceRules(data);
            return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
        } else {
            return new RespEntity(RespCode.ATTENDANCE_RULE_NAME_EXISTS);
        }

    }


    /**
     * 删除考勤信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/deleteAttendanceRules/{id}")
    @Transactional
    public RespEntity deleteAttendanceRules(@PathVariable("id") Integer id, HttpServletRequest request) {
        Integer userId = getUserId(request);
        if (userId == null) {
            return new RespEntity(RespCode.USER_NOT_FOUNT);
        }
        logger.info("/deleteAttendanceRules,id={}", id.toString());
        //首先判断该考勤规则是否和年级绑定了
        int count = attendanceRulesService.getAttendanceSetCountByRuleId(id);
        if (count > 0) {
            return new RespEntity(RespCode.ATTENDANCE_HAD_BINDING);
        }
        int i = attendanceRulesService.deleteAttendanceById(id);
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }


    /**
     * 获取用户id
     *
     * @return
     */
    public Integer getUserId(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        //获取用户的id
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        return (Integer) jsonObject.get("userId");
    }
}
